package com.jsonpfy.operations;

import java.util.ArrayList;
import java.util.Map;
import java.util.Map.Entry;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

/**
 * 
 * @Feature
 */
public class SaveArrayData {

	public static void doPut(Map<String, String[]> entityMap) {

		String kind = entityMap.get("kind")[0];

		String ID = entityMap.get("ID")[0];

		Entity entity = GetData.getEntity(kind, ID);

		if (entity != null) {

			DatastoreService datastore = DatastoreServiceFactory
					.getDatastoreService();

			for (Entry<String, String[]> mapEntry : entityMap.entrySet()) {

				String parameter = mapEntry.getKey();

				String[] values = mapEntry.getValue();

				if (!"kind".equals(parameter) && !"ID".equals(parameter)) {

					ArrayList<Key> arrayKey = new ArrayList<Key>();

					for (String stringValue : values) {

						if (!stringValue.equals("")) {

							Key key = KeyFactory.createKey(kind, stringValue);

							arrayKey.add(key);

						}
					}

					entity.setProperty(parameter, arrayKey);
				}
			}

			datastore.put(entity);
		}
	}
}